<template>
 <div style="margin: 15px">
<!--      搜索栏       -->
   <div>
     <el-form :inline="true"  class="demo-form-inline" >
     <el-form-item label="品牌名称">
       <el-input v-model="queryParams.name"  placeholder="请输入品牌名称" clearable />
     </el-form-item>
       <el-form-item>
         <el-button type="primary" icon="Search"  @click="initData">搜索</el-button>
         <el-button type="reset" icon="Refresh" @click="resetQueryParms" >重置</el-button>
       </el-form-item>
   </el-form>
   </div>

<!--   新增 修改  删除-->
   <div>
     <el-button type="primary" icon="Plus" @click="dialogVisible=true;tips='新增品牌'" v-hasPermi="['product:brand:add']" plain>新增</el-button>
     <el-button type="success" icon="Edit"  plain>修改</el-button>
     <el-button type="danger" icon="Delete" @click="handleBacheDel" plain>删除</el-button>
   </div>

<!--      表格      -->
   <div style="margin-top: 10px;margin-bottom: 20px">
     <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
       <el-table-column  type="selection" width="55" >
       </el-table-column>
       <el-table-column label="品牌名称" prop="name" width="120">
       </el-table-column>
       <el-table-column  label="品牌图标"  >
         <template #default="scope">
               <el-image style="width: 50px; height: 50px" :src="scope.row.logo" :fit="fit" />
         </template>
       </el-table-column>

       <el-table-column property="createTime" label="创建时间"  />
       <el-table-column property="opreation" label="操作"  >
         <template #default="scope">
<!--        修改 和 删除 按钮    -->
           <el-button icon="Edit" link type="primary" size="small"  @click="handleShowEditDialog(scope.row.id)">
             修改
           </el-button>
           <el-button icon="Delete" link type="danger" size="small"  @click="handleDelete(scope.row)">
             删除
           </el-button>

         </template>

       </el-table-column>

     </el-table>
   </div>


<!--   分页 -->
   <div class="demo-pagination-block" style="margin-left: 950">

     <el-pagination
         v-model:current-page="queryParams.pageNum"
         v-model:page-size="queryParams.pageSize"
         :page-sizes="[1, 2, 3, 4,10]"
         :size="size"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total"
         @size-change="initData"
         @current-change="initData"
     />
   </div>



   <!--   修改和新增的对话框-->
   <el-dialog
       v-model="dialogVisible"
       :title="tips"
       width="500"
       :before-close="handleClose"
   >

     <span>品牌名称 &ensp;</span><el-input v-model="brand.name" style="width: 240px" placeholder="Please input" >
   </el-input>
     <el-form-item label="品牌图标" :label-width="120">
       <el-upload
           class="avatar-uploader"
           :action="uploadUrl"
           :show-file-list="false"
           :name="file"
           :headers="headers"
           :on-success="handleUploadLogoSuccess"
       >
         <img v-if="brand.logo" :src="brand.logo" class="avatar"/>
         <el-icon v-else class="avatar-uploader-icon">
           <Plus/>
         </el-icon>
       </el-upload>
     </el-form-item>
<!--     单机事件 点击确定之后 发起触发方法 确定 即发起修改请求  取消更改dialogVisible-->
     <template #footer>
       <div class="dialog-footer">
         <el-button @click="dialogVisible = false">
           取消
         </el-button>
         <el-button type="primary" @click="handleSaveOrUpdate">
           确定
         </el-button>
       </div>
     </template>
   </el-dialog>



 </div>

</template>

<script setup>
import {listBrand,getbrand,addbrand,updatebrand,delbrand} from "@/api/product/brand.js"
import {ElMessage, ElMessageBox} from "element-plus";
import { getToken } from "@/utils/auth";
onMounted( () => {
    initData()
})




//表的数据 接收模型
const tableData =ref([])
//总页数接收模型
let total = ref(100)

const queryParams = ref({
  pageNum: 1,
  pageSize: 3,
  name: null
})
//页面分页查询发起异步请求
const initData =async ()=>{

   const {rows,total:t} =  await listBrand(queryParams.value)
    total.value=t
    tableData.value = rows;

}

//根据id查询name logo

let brand = ref({
  name:'',
  logo:null
})

//单机修改事件回显的函数  参数为品牌id
let dialogVisible =ref(false);

const handleShowEditDialog =async (id)=>{
  //单机事件之后 显示修改对话框
  tips.value="修改品牌"
  //根据id查询品牌
 const {data}=await getbrand(id);
    brand.value=data;
  dialogVisible.value=true
}

const tips=ref('')

const handleSaveOrUpdate =async ()=>{



//  做判断  如果brand中 有id说明是修改 没有id是新增
  if (brand.value.id){
    tips.value="修改品牌"
  //  修改
    await updatebrand(brand.value)
    ElMessage("修改成功！！！")
    initData()
    dialogVisible.value =false;
    brand.value=ref({
      name:'',
      logo:null
    })
  }else {
  //  新增
    tips.value="新增品牌"
    await addbrand(brand.value)
    ElMessage("添加成功")
    initData()
    brand.value=ref({
      name:'',
      logo:null
    })
  }

}


//删除函数 单机删除之后 显示是否删除 点击是 发起异步删除 否 关闭窗口回退
const handleDelete = (row)=>{
  ElMessageBox.confirm(
      "是否删除",{
        confirmButtonText :'删除',
        cancelButtonText:'取消删除'
      }
  ).then(
      async ()=>{

        await delbrand(row.id)
        initData()

      }
  ).catch(
      (e)=>{
        ElMessage("取消删除")
      }
  )
}

//  resetQueryParms 重置查询条件
const  resetQueryParms =async ()=>{
    queryParams.value.name=''
    initData()
}



 const selectionBrands = ref([])
//复选框的函数
const handleSelectionChange = (row)=>{
  selectionBrands.value = row
}



//批量删除
const  handleBacheDel = ()=>{
  const selectBrandNames = selectionBrands.value.map(brand => brand.name).join()
  let selectIds = selectionBrands.value.map((brand) => brand.id); //1,2,3
  if (!selectionBrands.value ||selectionBrands.value.length ===0 ){
    ElMessage.warning("未选择需要删除的品牌")
    return
  }else {

    ElMessageBox.confirm("是否删除",{
      confirmButtonText:'确定删除',
      cancelButtonText:'取消删除'
    }).then(async ()=>{

      await delbrand(selectIds)
      ElMessage("删除成功")
      initData()
    }).catch(
        (e)=>{
          ElMessage("取消删除")
        }
    )

  }

}
//  上传组件： 上传接口路径
const uploadUrl = import.meta.env.VITE_APP_BASE_API + "/file/upload"
//   上传组件： 报文头配置
const headers = {'Authorization':'Bearer '+getToken()}
//  上传组件： 上传成功的钩子函数
const handleUploadLogoSuccess = (r)=>{
  //后端响应报文状态码为200，前端认为成功
  if(+r.code === 200){ // +code表示将code转为数字
    //文件上传成功
    // console.log('文件上传成功:',r)
    // 获取上传成功的图片路径
    brand.value.logo = r.data.url;
  }else{
    //服务器响应成功 但是响应对象的 code值为失败
    ElMessage.error(r.msg)
  }
}


</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>

<style >
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>